import logging
import os
import webapp2

from db import model
from db.export_client import ExportClient
from db.export_client import ExportTable
from google.appengine.api import users
from google.appengine.ext.webapp import template


EXPORT_TABLES = [
  ExportTable.ANSWER,
  ExportTable.FRIEND_SURVEY,
  ExportTable.STRAINED_FRIEND_SURVEY,
  ExportTable.STUDENT,
  ExportTable.STUDENT_SESSION
]


BATCHES = [
  '1 - 4000',
  '4001 - 8000'
]


class ExportPage(webapp2.RequestHandler):
  def get(self):
    self.export_client = ExportClient()

    if (self.request.params.has_key('table') and
        self.request.params.has_key('session')):
      self.exportFile(self.request.params.get('table'),
          self.request.params.get('session'))
    else:
      self.displayExportPicker()

  def displayExportPicker(self):
    tmpl_data = {
      'export_tables': EXPORT_TABLES,
      'sessions': model.SESSIONS,
      'batches': BATCHES
    }
    path = os.path.join(os.path.dirname(__file__), 'export.html')
    self.response.out.write(template.render(path, tmpl_data))

  def exportFile(self, table, session):
    
    if table == ExportTable.ANSWER:
      export_file = self.export_client.exportAnswers(session)
    elif table == ExportTable.FRIEND_SURVEY:
      (start_index, end_index) = self.request.params.get('batch').split(' - ')
      export_file = self.export_client.exportFriendSurveys(
          session, int(start_index) - 1, int(end_index))
    elif table == ExportTable.STRAINED_FRIEND_SURVEY:
      export_file = self.export_client.exportStrainedFriendSurveys(session)
    elif table == ExportTable.STUDENT:
      export_file = self.export_client.exportStudents()
    elif table == ExportTable.STUDENT_SESSION:
      export_file = self.export_client.exportStudentSessions(session)

    if table == ExportTable.FRIEND_SURVEY:
      filename = \
          table + '_' + session + '_' + start_index + '-' + end_index + '.csv'
    elif table == ExportTable.STUDENT:
      filename = table + '.csv'
    else:
      filename = table + '_' + session + '.csv'

    self.response.headers['Content-Type'] = 'text/csv'
    self.response.headers['Content-Disposition'] = \
        str('attachment; filename=%s' % filename)
    self.response.out.write(export_file)


app = webapp2.WSGIApplication([
  ('/export', ExportPage),
], debug=True)
